package com.ty.admin.controller;

import com.ty.common.constant.Constants;
import com.ty.common.utils.Constant;
import com.ty.common.utils.JwtUtils;
import com.ty.common.utils.R;
import com.ty.skysystem.entity.UserEntity;
import com.ty.skysystem.entity.model.LoginUser;
import com.ty.skysystem.service.UserService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** @author Mjg @QQ:2091864671 @Creates by mjg ON 2020/12/22-19:39 */
@Slf4j
@RestController
@RequestMapping("admin")
public class LoginController {
  @Resource RedisTemplate<String, Object> redisTemplate;
  @Resource UserService userService;
  @Resource JwtUtils jwtUtils;

  @PostMapping("/login")
  public R login(@RequestBody LoginUser loginUser) {
    log.info("{}", loginUser);
    String code = (String) redisTemplate.opsForValue().get(Constant.VERIFICATION_CODE);
    log.info(" redis code {}", code);
    if (loginUser.getVerifyCode().equalsIgnoreCase(code)) {
      UserEntity login = userService.login(loginUser.getUsername(), loginUser.getPassword());
      log.info("{}", login);
      if (login != null) {
        String token = jwtUtils.createJwt(String.valueOf(login.getUserId()), login.getUserName());
        redisTemplate.opsForValue().set(Constants.TOKEN, token, 1, TimeUnit.HOURS);
        return R.ok("登录成功").put(token);
      }
      return R.error("用户名或密码错误");
    }
    return R.error("验证码错误");
  }

  @GetMapping("/logout")
  public R logout() {
    redisTemplate.delete(Constants.TOKEN);
    return R.ok("退出成功");
  }
}
